<?php
/**
 * Created by PhpStorm.
 * User: yuyiwen
 * Date: 2018/9/5
 * Time: 下午3:01
 */

namespace app\admin\controller;


use think\Controller;
use think\Request;

class Common  extends Controller
{
    public function _initialize ()
    {
        // 判断是否登录
        if (session('admin_id') == null || session('admin_nickname') == ''){
            $this->error('请先登录' , 'log/login');
        }
        $this->check_auth();

           $menus =  $this->build_menus();

        $this->assign('menus' , $menus);
    }

    public function check_auth ()
    {
        $permission_ids = session('permission_ids' );
       $request = Request::instance();
       $module = $request->module();
       $controller = $request->controller();
       $action = $request->action();

       $permission = model('permission');
       $permission_list = $permission->getPermission($permission_ids);

       $role_ids = explode(',',session('role_ids'));
       if (in_array(1 , $role_ids)){
            $hasPermission = 1;
       }else{
           $hasPermission = 0;
           foreach ($permission_list as $key => $value)
           {
               if (strtolower($value['permission']) == strtolower($module . '/' . $controller . '/' . $action)){
                   $hasPermission = 1;
                   break;
               }
           }
       }

       if (!$hasPermission)
       {
           $this->error('没有权限' , url('index/index'));
       }
        $this->assign('current_item' ,  strtolower($module . '/' . $controller . '/' . $action));
    }

    /**
     * 生成权限菜单
     */
    public function build_menus ()
    {
        $permission = model('permission');
        $menus = $permission->getMenus (session('permission_ids' ));
        return $menus;
//        session(session('admin_id').'menus' , $menus);
    }
}